package com.weiaibenpao.demo.chislim.hurui.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.loopj.android.http.HttpGet;
import com.squareup.picasso.Picasso;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.adater.MusicListAdapter;
import com.weiaibenpao.demo.chislim.bean.Li_MusicResult;
import com.weiaibenpao.demo.chislim.map.customview.CircleImageView;
import com.weiaibenpao.demo.chislim.music.SendData.SendDataListener;
import com.weiaibenpao.demo.chislim.music.bean.Bean_music;
import com.weiaibenpao.demo.chislim.music.dao.Dao_Get_music;
import com.weiaibenpao.demo.chislim.music.service.Start_Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import cz.msebera.android.httpclient.message.BasicHeader;


public class HMuiscListActivity extends HBaseActivity implements SendDataListener {
    @BindView(R.id.topImg)
    ImageView topImg;
    @BindView(R.id.titleImg)
    CircleImageView titleImg;
    @BindView(R.id.localMusicListView)
    RecyclerView localMusicListView;

    private String downloadPath = "/mnt/sdcard";
    private RelativeLayout head_layout1;
    private int postion;  //当前播放歌曲的序列号
    //获取本地歌曲数据源
    private Dao_Get_music get_music;
    //用来存放本地歌曲
    private ArrayList<Bean_music> localMusicList;
    //定义适配器
    private MusicListAdapter localMusicAdapter;

    Toolbar mToolbar;
    CollapsingToolbarLayout mCollapsingToolbarLayout;
    AppBarLayout app_bar_layout;
    Context context;

    Li_MusicResult.DataBean musicResult;
    int n;
    ArrayList musiclist;

    //服务
    private Intent intentservice;
    private Start_Service start_service;  //服务对象

    private DownloadAsyncTask downloadTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hmuisc_list);
        ButterKnife.bind(this);
        context = getApplicationContext();
        app_bar_layout = (AppBarLayout) findViewById(R.id.app_bar_layout);
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        head_layout1 = (RelativeLayout) findViewById(R.id.head_layout1);
        //使用CollapsingToolbarLayout必须把title设置到CollapsingToolbarLayout上，设置到Toolbar上则不会显示
        mCollapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_layout);
        get_music = new Dao_Get_music(context);
        //电话监听
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        telephonyManager.listen(new MyPhoneListener(), PhoneStateListener.LISTEN_CALL_STATE);


        //获取传递过来的数据
        getData();

        //设置顶部布局
        setTopView();

        //获取本地歌曲
        getLocalData();
    }

    /**
     * 获取传递过来的数据
     */
    public void getData() {
        Bundle bundle = getIntent().getExtras();

        n = bundle.getInt("num", 1);
        musicResult = (Li_MusicResult.DataBean) bundle.getSerializable("musicResult");
        musiclist = (ArrayList<Li_MusicResult.DataBean.MusicTypelistBean>) musicResult.getMusicTypelist();

    }

    /**
     * 设置顶部布局
     */
    public void setTopView() {
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        app_bar_layout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset <= -head_layout1.getHeight() / 2) {
                    mCollapsingToolbarLayout.setTitle("我的音乐");
                } else {
                    mCollapsingToolbarLayout.setTitle(" ");
                }
            }
        });
        Log.i("图片",((Li_MusicResult.DataBean.MusicTypelistBean) musiclist.get(n-1)).getMusicTypeImg());
        Picasso.with(context)
                .load(((Li_MusicResult.DataBean.MusicTypelistBean) musiclist.get(n-1)).getMusicTypeImg())
                //.placeholder()
                //.error()
                .into(topImg);
        Picasso.with(context)
                .load(((Li_MusicResult.DataBean.MusicTypelistBean)musiclist.get(n-1)).getMusicTypeImg())
                //.placeholder()
                //.error()
                .into(titleImg);
    }

    /**
     * 获取本地歌曲
     */
    public void getLocalData() {
        localMusicListView.setLayoutManager(new LinearLayoutManager(this,
                LinearLayoutManager.VERTICAL,false));
        //获取本地歌曲
        localMusicList = get_music.getMusic_Array();

        localMusicAdapter = new MusicListAdapter(context,n, localMusicList, musiclist); //第二个  本地歌曲   第三个 网络歌曲


        localMusicListView.setAdapter(localMusicAdapter);

        localMusicAdapter.setOnItemClickListener(new MusicListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, int state) {
                if(state == 0){            //歌曲未下载,从网络歌曲里表的连接中下载
                    Log.i("路径",((Li_MusicResult.DataBean.MusicTypelistBean) musiclist.get(n-1)).getMusicList().get(position).getMusicUrl());
                    downloadTask = new DownloadAsyncTask(((Li_MusicResult.DataBean.MusicTypelistBean) musiclist.get(n-1)).getMusicList().get(position).getMusicUrl());
                    localMusicAdapter.setAnimationView(position);
                    localMusicAdapter.notifyDataSetChanged();
                    downloadTask.execute();
                }else{                          //否则从本地歌曲中播放
                    if(!start_service.getState()){
                        start_service.play(0, localMusicList.get(position),position);
                    }else{
                        start_service.pause();
                    }
                }
            }
        });

    }

    @Override
    public void sendPos(int position) {
        this.postion = position;
    }


    /**
     * 只有电话来了之后才暂停音乐的播放
     */
    private final class MyPhoneListener extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING://电话来了
                    start_service.pause();
                    break;
                case TelephonyManager.CALL_STATE_IDLE: //通话结束
                    //player.callIsDown();
                    break;
            }
        }
    }

    /**
     * 启动服务,向服务中传本地歌曲localMusicList
     */
    @Override
    public void onStart() {
        super.onStart();

        intentservice = new Intent(HMuiscListActivity.this, Start_Service.class);
        Bundle bundle = new Bundle();
        //getFraMusic();   //获取本地歌曲数据源
        bundle.putParcelableArrayList("music", localMusicList);
        intentservice.putExtras(bundle);

        startService(intentservice);
        bundle.putInt("postion", 0);
        getApplicationContext().bindService(intentservice, connection, Context.BIND_AUTO_CREATE);
    }

    /**
     * 获取服务对象
     */
    public ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Start_Service.My_binder binder = (Start_Service.My_binder) service;
            start_service = binder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            start_service.onDestroy();
        }
    };

    /**
     * 下载的AsyncTask
     */
    private class DownloadAsyncTask extends AsyncTask<String, Integer, Long> {
        private static final String TAG = "DownloadAsyncTask";
        private String mUrl;

        public DownloadAsyncTask(String url) {
            this.mUrl = url;
        }

        @Override
        protected Long doInBackground(String... params) {
            if (mUrl == null) {
                return null;
            }
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet(mUrl);
            HttpResponse response = null;
            InputStream is = null;
            RandomAccessFile fos = null;
            OutputStream output = null;

            try {
                //创建存储文件夹
                File dir = new File(downloadPath);
                if (!dir.exists()) {
                    dir.mkdir();
                }
                //本地文件
                File file = new File(downloadPath + File.separator + mUrl.substring(mUrl.lastIndexOf("/") + 1));
                if (!file.exists()) {
                    //创建文件输出流
                    output = new FileOutputStream(file);
                    //获取下载输入流
                    response = client.execute(request);
                    is = response.getEntity().getContent();
                    //写入本地
                    file.createNewFile();
                    byte buffer[] = new byte[1024];
                    int inputSize = -1;
                    //获取文件总大小，用于计算进度
                    long total = response.getEntity().getContentLength();
                    int count = 0; //已下载大小
                    while ((inputSize = is.read(buffer)) != -1) {
                        output.write(buffer, 0, inputSize);
                        count += inputSize;
                        //更新进度
                        this.publishProgress((int) ((count / (float) total) * 100));
                        //一旦任务被取消则退出循环，否则一直执行，直到结束
                        if (isCancelled()) {
                            output.flush();
                            return null;
                        }
                    }
                    output.flush();
                } else {
                    long readedSize = file.length(); //文件大小，即已下载大小
                    //设置下载的数据位置XX字节到XX字节
                    Header header_size = new BasicHeader("Range", "bytes=" + readedSize + "-");
                    request.addHeader(header_size);
                    //执行请求获取下载输入流
                    response = client.execute(request);
                    is = response.getEntity().getContent();
                    //文件总大小=已下载大小+未下载大小
                    long total = readedSize + response.getEntity().getContentLength();

                    //创建文件输出流
                    fos = new RandomAccessFile(file, "rw");
                    //从文件的size以后的位置开始写入，其实也不用，直接往后写就可以。有时候多线程下载需要用
                    fos.seek(readedSize);
                    //这里用RandomAccessFile和FileOutputStream都可以，只是使用FileOutputStream的时候要传入第二哥参数true,表示从后面填充
//                    output = new FileOutputStream(file, true);

                    byte buffer[] = new byte[1024];
                    int inputSize = -1;
                    int count = (int) readedSize;
                    while ((inputSize = is.read(buffer)) != -1) {
                        fos.write(buffer, 0, inputSize);
//                        output.write(buffer, 0, inputSize);
                        count += inputSize;
                        this.publishProgress((int) ((count / (float) total) * 100));
                        if (isCancelled()) {
//                            output.flush();
                            return null;
                        }
                    }
//                    output.flush();
                }
            } catch (MalformedURLException e) {
                Log.e(TAG, e.getMessage());
            } catch (IOException e) {
                Log.e(TAG, e.getMessage());
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                    if (output != null) {
                        output.close();
                    }
                    if (fos != null) {
                        fos.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPreExecute() {
            Log.i(TAG, "download begin ");
            Toast.makeText(HMuiscListActivity.this, "开始下载", Toast.LENGTH_SHORT).show();
            super.onPreExecute();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            Log.i(TAG, "downloading  " + values[0]);
            //更新界面进度条
            // progressBar.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(Long aLong) {
            Log.i(TAG, "download success " + aLong);
            Toast.makeText(HMuiscListActivity.this, "下载结束", Toast.LENGTH_SHORT).show();
            localMusicList = get_music.getMusic_Array();
            setCompeteStatus();
            super.onPostExecute(aLong);
        }
    }

    public void setCompeteStatus() {
       // scanFile(context,"");
        //检查sd卡上的媒体文件
        ///sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + Environment.getExternalStorageDirectory().getAbsolutePath())));
        //sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
        Log.i("本地歌曲","-------"+ localMusicList.size() + "-------");
        localMusicAdapter.setAnimationView(-10);
        localMusicAdapter.ReFreshen(localMusicList);
    }

    /**
     * 通知媒体库更新文件
     * @param context
     * @param filePath 文件全路径
     *
     * */
    public void scanFile(Context context, String filePath) {
        Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        scanIntent.setData(Uri.fromFile(new File(filePath)));
        context.sendBroadcast(scanIntent);
    }
}
